// 导入axios
import axios from 'axios'
// 导入饿了么提示框
import { MessageBox, Message } from 'element-ui'
// 导入vuex实例
import store from '@/store'
// 导入设置token的函数
import { getToken } from '@/utils/auth'

// 初始化创建一个axios
const service = axios.create({
  // 设置基础地址
  baseURL: process.env.VUE_APP_BASE_API,
  // 设置时间超时，单位毫秒
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 请求成功做什么
    if (store.getters.token) {
      // 如果getters有token，设置请求头token
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // 请求失败做什么
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  //  响应成功做些什么
  response => {
    // 声明响应数据
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          // 调用veux里函数移除token
          store.dispatch('user/resetToken').then(() => {
            location.reload() // 强制刷新浏览器
          })
        })
      }
      // 返回 axios 调用处 一个reject错误promise对象
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
